import axios from 'axios'
import config from '@/request/config'
import store from '@/store'
import { debounce } from '@/utils/tool'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 配置axios适配器
axios.defaults.adapter = (config) => {
	return new Promise((resolve, reject) => {
		const header = {
			...config.headers,  // 保留原有headers
			'Content-Type': config.headers['Content-Type'] || 'application/json;charset=utf-8'
		}
		
		uni.request({
			url: config.baseURL + config.url,
			method: config.method.toUpperCase(),
			header,  // 使用处理后的header
			data: config.data,
			timeout: config.timeout,
			success: (res) => {
				return resolve({
					data: res.data,
					status: res.statusCode,
					headers: res.header,
					config: config
				})
			},
			fail: (err) => {
				return reject(err)
			}
		})
	})
}

// 创建axios实例
const network = axios.create({
	// axios中请求配置有baseURL选项，表示请求URL公共部分
	baseURL: config.getServerUrl(),
	// 超时
	timeout: 15 * 1000
})

network.beforeRequest = []
network.nextResponse = []

network.addBeforRequest = fn => {
	if (!network.beforeRequest.includes(fn)) {
		network.beforeRequest.push(fn)
	}
}
network.removeBeforRequest = fn => {
	if (network.beforeRequest.includes(fn)) {
		network.beforeRequest.findIndex((item, index) => {
			if (item === fn) {
				network.beforeRequest.splice(index, 1)
			}
		})
	}
}
network.addNextResponse = fn => {
	if (!network.nextResponse.includes(fn)) {
		network.nextResponse.push(fn)
	}
}
network.removeNextResponse = fn => {
	if (network.nextResponse.includes(fn)) {
		network.nextResponse.findIndex((item, index) => {
			if (item === fn) {
				network.nextResponse.splice(index, 1)
			}
		})
	}
}

const requestCallback = request => {
	network.beforeRequest.forEach(item => {
		item(request)
	})
}

const responseCallback = response => {
	network.nextResponse.forEach(item => {
		item(response)
	})
}

network.interceptors.request.use(config => {
	let token = uni.getStorageSync('token')
	if (token && token.length > 0) {
		// 确保headers对象存在
		config.headers = config.headers || {}
		config.headers['Authorization'] = token
	}
	
	requestCallback(config)
	return config
})

const handle401Action = debounce(() => {
	store.dispatch('user/logout').then(() => {
		uni.reLaunch({
			url: '/pages/login/index'
		})
	})
}, 1000, true)  // 立即执行

network.interceptors.response.use(res => {
	responseCallback(res)
	switch (res.status) {
		case 200:
			if (res.data.code == 200) {
				return Promise.resolve(res.data)
			} else if (res.data.code == 401) {
				handle401Action()
			} else {
				setTimeout(()=>{
					uni.showToast({
						title:res.data.msg || '',
						icon:'none',
						duration:2000
					})
				},100)
				return Promise.reject(res.data)
			}
	}
	return Promise.reject(res)
}, error => {
	responseCallback(error)
	if (error.response.status == 401) {
		handle401Action()
	} else {
		// uni.showToast({
		// 	title:'服务器处理异常',
		// 	icon:'none'
		// })
		// Message.error("服务器处理异常 " + error)
	}
	return Promise.reject(error)
})

//删除之前的adapter相关代码，直接导出
export default network
